#include <stdio.h>
#include "radar.h"
#include "esp_log.h"
#include "freertos/FreeRTOS.h"
#include "driver/gpio.h"

static const char *TAG = "radar";

// static uint8_t radar_flag = 0;
static uint8_t last_io_level = 0;
static uint8_t io_level = 0;

#define RADAR_GPIO_PIN 6

static uint8_t radar_inited = 0;



void radar_init(void)
{
    gpio_config_t io_conf = {
        .pin_bit_mask = (1ULL << RADAR_GPIO_PIN), 
        .mode = GPIO_MODE_INPUT,
        .pull_up_en = GPIO_PULLUP_DISABLE,
        .pull_down_en = GPIO_PULLDOWN_ENABLE,
        .intr_type = GPIO_INTR_DISABLE
    };
    gpio_config(&io_conf);

    
    ESP_LOGI(TAG, "Radar initialized");
}


void radar_ms_handle()
{
    static uint32_t running_time = 0;
    static uint16_t ms_counter = 0;
    if(radar_inited == 0)
    {
        running_time ++; // Assuming this function is called every 100ms

        if (running_time >= 3000) { // 3 seconds has passed
      
            running_time = 0;
            radar_inited = 1; // Set radar as initialized
        }
    }else{

        ms_counter++;
        if (ms_counter >= 100) { // 100ms has passed
            ms_counter = 0;
            io_level = gpio_get_level(RADAR_GPIO_PIN);
            if (io_level != last_io_level) {
                last_io_level = io_level;
                if(io_level == 1)
                {
                    ESP_LOGI(TAG, "Radar detected trigger");
                    // Add your radar processing logic here
                    // For example, you can send a signal or perform an action
                } else {
                    ESP_LOGI(TAG, "Radar detected cancel");
                    // Handle radar cancel logic here   
                }
            }
            
        }

    }

    
    

}